package encaps.utils;

import encaps.action.ActionContext;
import encaps.resources.Config;
import encaps.resources.Labels;
import java.io.*;
import java.util.Scanner;

public class IOHelper {

    private static final int BUFFER_SIZE = 1024;

    private IOHelper() {
    }

    public static String uploadFile(ActionContext context, String fileControlName,
            String fileName, String directory) throws SystemException {
        String imageType = context.getImageType(fileControlName);
        if (imageType == null) {
            return null;
        }
        String fullFileName = fileName + "." + imageType;
        InputStream pictureStream = context.getFileInputStream(fileControlName);
        String picturePath = IOHelper.writeFile(pictureStream, directory, fullFileName);
        return picturePath;
    }

    public static String writeFile(InputStream in, String path, String fileName) throws SystemException {
        FileOutputStream out = null;
        try {
            File directory = new File(path);
            if (!directory.exists() || (directory.exists() && !directory.isDirectory())) {
                directory.mkdir();
            }
            File outputFile = new File(directory, fileName);
            out = new FileOutputStream(outputFile);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len = in.read(buffer);
            if (len < 0) {
                return Config.getDefaultImage();
            }
            while (len > 0) {
                out.write(buffer, 0, len);
                len = in.read(buffer);
            }
            return outputFile.getAbsolutePath();
        } catch (IOException ex) {
            throw new SystemException(Labels.getLabel(Labels.CANNOT_WRITE_FILE_MESSAGE), ex);
        } finally {
            closeStream(in);
            closeStream(out);
        }
    }

    public static void closeStream(InputStream stream) {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (Exception ex) {
        }
    }

    public static void closeStream(OutputStream stream) {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (Exception ex) {
        }
    }

    public static void closeScanner(Scanner s) {
        try {
            if (s != null) {
                s.close();
            }
        } catch (Exception ex) {
        }
    }
}
